package com.cunyme;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.apache.http.cookie.Cookie;
import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class Download_helper extends Activity implements Runnable
{
	
    ProgressDialog dialog;
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
		
		String url_temp_string = getIntent().getExtras().getString("url");
		String[] url_components = url_temp_string.split("/");
		String url_string = "https://bbhosted.cuny.edu";
		for (int i = 2; i < url_components.length; i++)
		{
			url_string += "/" + url_components[i];
		}
					
		String fileName = url_components[url_components.length - 1];
		String directoryName = url_components[url_components.length - 4];
        
        
		dialog = new ProgressDialog(Download_helper.this);

		// make the progress bar cancelable
		dialog.setCancelable(true);
		
		// set a message text
		dialog.setMessage("Downloading " + fileName + " to " + Environment.getExternalStorageDirectory() + "/blackboard/" + directoryName + "/");
		
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setProgress(0);
        
		// show it
		dialog.show();
		
		Thread thread = new Thread(Download_helper.this);
		thread.start();
    } 
        
    public void run()
    {   
		SQLiteDatabase cuny_meDB = openOrCreateDatabase("cuny_me.db", Context.MODE_PRIVATE, null);
        helper_functions helpers = new helper_functions();
		//Map <String, String> portal_cookies = helpers.getcookies("portal", cuny_meDB);
		Map <String, String> blackboard_cookies = helpers.getcookies("blackboard", cuny_meDB);
		cuny_meDB.close();
			
		try
		{	
			String url_temp_string = getIntent().getExtras().getString("url");
			String[] url_components = url_temp_string.split("/");
			String url_string = "https://bbhosted.cuny.edu";
			for (int i = 2; i < url_components.length; i++)
			{
				url_string += "/" + url_components[i];
			}
						
			String fileName = url_components[url_components.length - 1];
			String directoryName = url_components[url_components.length - 4];
			URL url = new URL(url_string); //you can write here any link
			//URL url = new URL("https://bbhosted.cuny.edu/courses/1/HUNTR_CSCI_41500_051_201009/content/_4842420_1/CS415SyllabusFall10V1.6.doc?bsession=62501120&bsession_str=session_id=62501120,user_id_pk1=710540,user_id_sos_id_pk2=1,one_time_token="); //you can write here any link

			File blackboardDirectory = new File(Environment.getExternalStorageDirectory() + "/blackboard/" + directoryName + "/");
			if(!blackboardDirectory.exists())
				blackboardDirectory.mkdirs();
			
			File file = new File(Environment.getExternalStorageDirectory() + "/blackboard/" + directoryName + "/" + fileName);
		 
		    Log.d("ImageManager", "download begining");
		    Log.d("ImageManager", "download url:" + url);
		    Log.d("ImageManager", "downloaded file name:" + fileName);
		    // Open a connection to that URL.
		     URLConnection ucon = url.openConnection();
		     
		     String cookieString = null;
		     /*for (Map.Entry<String, String> entry : portal_cookies.entrySet())
		     {
		        String key = entry.getKey();
		        String value = entry.getValue();
		        cookieString = cookieString + key + "=" + value + "; ";
		     }*/
		     for (Map.Entry<String, String> entry : blackboard_cookies.entrySet())
		     {
		        String key = entry.getKey();
		        String value = entry.getValue();
		        cookieString = cookieString + key + "=" + value + "; ";
		     }
			    ucon.setRequestProperty("cookie", cookieString);
			    //ucon.connect();

		    
		   // Define InputStreams to read from the URLConnection.
		    
		    InputStream is = ucon.getInputStream();
		    BufferedInputStream bis = new BufferedInputStream(is);
	        dialog.setMax(ucon.getContentLength());
		    
		    //Read bytes to the Buffer until there is nothing more to read(-1).
		    
		    ByteArrayBuffer baf = new ByteArrayBuffer(50);
		    int current = 0;
		    while ((current = bis.read()) != -1)
		    {
		    	baf.append((byte) current);
		        dialog.incrementProgressBy(1);
		    }
		 
		    // Convert the Bytes read to a String.
		    FileOutputStream fos = new FileOutputStream(file);
		    fos.write(baf.toByteArray());
		    fos.close();
			success_handler.sendEmptyMessage(0);
		 }
		catch (IOException e)
		{
		    Log.d("ImageManager", "Error: " + e);
			failure_handler.sendEmptyMessage(0);
		}
    }
    
    @Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	private Handler success_handler = new Handler()
    {
    	@Override
    	public void handleMessage(Message msg)
    	{
    		dialog.dismiss();
			//Toast.makeText(getApplicationContext(), "Download successful!", Toast.LENGTH_LONG).show();
    		AlertDialog.Builder builder = new AlertDialog.Builder(Download_helper.this);
			builder.setMessage("Download Successful!")
			       .setCancelable(false)
			       .setNeutralButton("Return", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id)
			           {
			       			finish();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
    	}
    };
    private Handler failure_handler = new Handler()
    {
    	@Override
    	public void handleMessage(Message msg)
    	{
			dialog.dismiss();
			//Toast.makeText(getApplicationContext(), "Error downloading file.  Please try again later.", Toast.LENGTH_LONG).show();
    		AlertDialog.Builder builder = new AlertDialog.Builder(Download_helper.this);
			builder.setMessage("Error downloading file.  Please try again later.")
			       .setCancelable(false)
			       .setNeutralButton("Return", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id)
			           {
			       			finish();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
    	}
    };    
}
